package aliyun.cx.admin.controller;

import aliyun.cx.service.entity.SysConfig;
import aliyun.cx.service.service.SysConfigService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 系统配置控制器
 */
@RestController
@RequestMapping("/api/system/config")
@CrossOrigin(origins = "*", maxAge = 3600)
public class SysConfigController {

    private final SysConfigService sysConfigService;
    
    public SysConfigController(SysConfigService sysConfigService) {
        this.sysConfigService = sysConfigService;
    }

    /**
     * 获取系统配置列表
     */
    @GetMapping("/list")
    public Map<String, Object> getConfigList(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String configKey,
            @RequestParam(required = false) String configName) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 构建查询条件
            QueryWrapper<SysConfig> queryWrapper = new QueryWrapper<>();
            
            if (configKey != null && !configKey.trim().isEmpty()) {
                queryWrapper.like("config_key", configKey);
            }
            
            if (configName != null && !configName.trim().isEmpty()) {
                queryWrapper.like("config_name", configName);
            }
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc("create_time");
            
            // 分页查询
            Page<SysConfig> pageParam = new Page<>(current, size);
            IPage<SysConfig> configPage = sysConfigService.page(pageParam, queryWrapper);
            
            // 添加调试日志
            System.out.println("分页查询结果: " + configPage);
            System.out.println("总记录数: " + configPage.getTotal());
            System.out.println("当前页: " + configPage.getCurrent());
            System.out.println("页大小: " + configPage.getSize());
            System.out.println("总页数: " + configPage.getPages());
            System.out.println("记录数: " + configPage.getRecords().size());
            
            result.put("code", 200);
            result.put("message", "获取配置列表成功");
            result.put("data", configPage);
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取配置列表失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 根据ID获取系统配置
     */
    @GetMapping("/{id}")
    public Map<String, Object> getConfigById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            SysConfig config = sysConfigService.getById(id);
            
            if (config != null) {
                result.put("code", 200);
                result.put("message", "获取配置成功");
                result.put("data", config);
            } else {
                result.put("code", 404);
                result.put("message", "配置不存在");
            }
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取配置失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 根据配置键获取配置值
     */
    @GetMapping("/value/{configKey}")
    public Map<String, Object> getConfigValue(@PathVariable String configKey) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String configValue = sysConfigService.getConfigValue(configKey);
            
            result.put("code", 200);
            result.put("message", "获取配置值成功");
            result.put("data", configValue);
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取配置值失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 创建系统配置
     */
    @PostMapping("/create")
    public Map<String, Object> createConfig(@RequestBody SysConfig config) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = sysConfigService.save(config);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "创建配置成功");
                result.put("data", config);
            } else {
                result.put("code", 400);
                result.put("message", "创建配置失败");
            }
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "创建配置失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 更新系统配置
     */
    @PutMapping("/update")
    public Map<String, Object> updateConfig(@RequestBody SysConfig config) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = sysConfigService.updateById(config);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "更新配置成功");
                result.put("data", config);
            } else {
                result.put("code", 400);
                result.put("message", "更新配置失败");
            }
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "更新配置失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 删除系统配置
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteConfig(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 先检查是否为系统配置
            SysConfig config = sysConfigService.getById(id);
            if (config != null && config.getIsSystem()) {
                result.put("code", 400);
                result.put("message", "系统配置项不可删除");
                return result;
            }
            
            boolean success = sysConfigService.removeById(id);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "删除配置成功");
            } else {
                result.put("code", 400);
                result.put("message", "删除配置失败");
            }
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "删除配置失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 刷新配置缓存
     */
    @PostMapping("/refresh-cache")
    public Map<String, Object> refreshConfigCache() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            sysConfigService.refreshConfigCache();
            result.put("code", 200);
            result.put("message", "刷新配置缓存成功");
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "刷新配置缓存失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取配置状态（用于前端检查功能是否启用）
     */
    @GetMapping("/status")
    public Map<String, Object> getConfigStatus() {
        try {
            Map<String, Object> result = new HashMap<>();
            Map<String, Object> status = new HashMap<>();
            
            // 从数据库获取配置状态
            status.put("uploadEnabled", "true".equals(sysConfigService.getConfigValue("upload.enabled", "true")));
            status.put("maxFileSize", sysConfigService.getConfigValue("upload.maxFileSize", "5242880"));
            status.put("allowedFileTypes", sysConfigService.getConfigValue("upload.allowedTypes", "jpg,jpeg,png,gif,webp"));
            
            // 系统监控相关配置
            status.put("monitorEnabled", "true".equals(sysConfigService.getConfigValue("monitor.enabled", "true")));
            status.put("monitorInterval", sysConfigService.getConfigValue("monitor.interval", "300"));
            
            // 备份相关配置
            status.put("autoBackupEnabled", "true".equals(sysConfigService.getConfigValue("backup.autoBackup", "true")));
            status.put("backupRetentionDays", sysConfigService.getConfigValue("backup.retentionDays", "30"));
            status.put("backupTime", sysConfigService.getConfigValue("backup.backupTime", "02:00"));
            
            // 缓存相关配置
            status.put("cacheEnabled", "true".equals(sysConfigService.getConfigValue("cache.enabled", "true")));
            status.put("cacheTTL", sysConfigService.getConfigValue("cache.ttl", "3600"));
            
            // 日志相关配置
            status.put("logRetentionDays", sysConfigService.getConfigValue("log.retentionDays", "90"));
            
            // 系统相关配置
            status.put("sessionTimeout", sysConfigService.getConfigValue("system.sessionTimeout", "7200"));
            status.put("defaultPageSize", sysConfigService.getConfigValue("system.pageSize", "10"));
            
            // 邮件相关配置
            status.put("emailEnabled", "true".equals(sysConfigService.getConfigValue("email.smtp.host", "")));
            status.put("smtpHost", sysConfigService.getConfigValue("email.smtp.host", ""));
            status.put("smtpPort", sysConfigService.getConfigValue("email.smtp.port", "587"));
            status.put("smtpSslEnabled", "true".equals(sysConfigService.getConfigValue("email.smtp.ssl", "true")));
            
            // 功能模块配置状态
            status.put("articlePublishEnabled", "true".equals(sysConfigService.getConfigValue("article.publish.enabled", "true")));
            status.put("commentPublishEnabled", "true".equals(sysConfigService.getConfigValue("comment.publish.enabled", "true")));
            status.put("userRegisterEnabled", "true".equals(sysConfigService.getConfigValue("user.register.enabled", "true")));
            status.put("categoryCreateEnabled", "true".equals(sysConfigService.getConfigValue("category.create.enabled", "true")));
            status.put("tagCreateEnabled", "true".equals(sysConfigService.getConfigValue("tag.create.enabled", "true")));
            
            result.put("code", 200);
            result.put("message", "获取配置状态成功");
            result.put("data", status);
            
            return result;
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "获取配置状态失败：" + e.getMessage());
            return result;
        }
    }
}
